//
//  MedicalRecordViewModel.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2021/8/19.
//  Copyright © 2021 QDSG. All rights reserved.
//

import UIKit

private let defaultSections = [
    MedicalRecordSection(mode: .patientInfo),
    MedicalRecordSection(mode: .mainState),
    MedicalRecordSection(mode: .picture),
    MedicalRecordSection(mode: .illnessHistory),
    MedicalRecordSection(mode: .pastHistory),
    MedicalRecordSection(mode: .specialCheck),
    MedicalRecordSection(mode: .diagnose),
    MedicalRecordSection(mode: .opinion),
    MedicalRecordSection(mode: .sign)
]

class MedicalRecordViewModel: NSObject {
    var updateClosure: (() -> ())?
    
    private var items: [MedicalRecordCellViewModel] = []
    
    private let sections = defaultSections
    
    private var model = MedicalRecordDetail() {
        didSet {
            handleItems()
            updateClosure?()
        }
    }
    
    var hospitalName: String? { model.hospitalName }
    
    var numberOfSections: Int { items.count }
    
    var numberOfRows: Int { 1 }
    
    func headerHeight(in section: Int) -> CGFloat {
        let viewModel = viewModel(in: section)
        switch viewModel.mode {
        case .mainState,
             .opinion: return 10
        default:       return 0.001
        }
    }
    
    func viewModel(in section: Int) -> MedicalRecordCellViewModel {
        items[section]
    }
    
    private func handleItems() {
        items = sections.map { section -> MedicalRecordSection in
            var tempSection = section
            tempSection.model = model
            return tempSection
        }.map { MedicalRecordCellViewModel(with: $0) }
    }
}

extension MedicalRecordViewModel {
    /// 获取电子病历详情
    func getMedicalRecordDetail(diagnoseId: String) {
        HUDTool.showActivity()
        let target = ApiManager.medicalRecordDetail(diagnoseId: diagnoseId)
        HttpTool.shared.request(target: target) { json, code in
            YSGLog("电子病历详情 json: \(json)")
            HUDTool.hideActivity()
            switch code {
            case .failure:
                HUDTool.showError(message: json["message"].description)
            case .success:
                if let model = MedicalRecordDetail.deserialize(from: json["data"].description) {
                    self.model = model
                }
            }
        } failure: { error in
            HUDTool.hideActivity()
            HUDTool.showError(message: error?.description)
        }

    }
}
